package com.xqb.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * @Author: JinChen Zhu
 * @CreateTime: 2024-10-31  00:47
 */
@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    public void sendEmail(String to, String subject, String templateName, Map<String, Object> model) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(generateHtmlFromTemplate(templateName, model), true);

        mailSender.send(mimeMessage);
    }

    private String generateHtmlFromTemplate(String templateName, Map<String, Object> model) throws MessagingException {
        try {
            return FreeMarkerTemplateUtils.processTemplateIntoString(freeMarkerConfigurer.createConfiguration().getTemplate(templateName), model);
        } catch (Exception e) {
            throw new MessagingException("Failed to generate email content", e);
        }
    }
}